﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Windows.Forms;
using Autodesk.Revit.DB;
using Autodesk.Revit.DB.Mechanical;
using Autodesk.Revit.UI;
using YArchitech.Controls;
using YArchitech.HYSpace.SpaceManager.Manager;
using YArchitech.LIB;
using YArchitech.Revit;
using Microsoft.Win32;

namespace YArchitech.HYSpace.SpaceManager.Forms
{
	public partial class SpaceManagerForm : System.Windows.Forms.Form
	{
		public SpaceManagerForm()
		{
			this.InitializeComponent();
		}

		public SpaceManagerForm(UIApplication app, DataManager dataManager)
		{
			this.InitializeComponent();
			this.m_uiApp = app;
			this.m_dataManager = dataManager;
			this.chkShowElement.Checked = false;
			this.InitZoneList();
		}

		private void InitSpaceTree(Zone zone)
		{
			Dictionary<int, List<Space>> dictionary = new Dictionary<int, List<Space>>();
			dictionary.Clear();
			this.spaceTreeView.Nodes.Clear();
			SpaceSet spaceSet;
			if (zone != null)
			{
				spaceSet = zone.Spaces;
			}
			else
			{
				spaceSet = new SpaceSet();
				spaceSet = this.m_dataManager.GetSpacesInDefaultZone();
			}
			foreach (object obj in spaceSet)
			{
				Space space = (Space)obj;
				ElementId levelId = space.LevelId;
				if (!(levelId == null))
				{
					if (!dictionary.ContainsKey(levelId.IntegerValue))
					{
						dictionary.Add(levelId.IntegerValue, new List<Space>());
					}
					dictionary[levelId.IntegerValue].Add(space);
				}
			}
			foreach (KeyValuePair<int, List<Space>> keyValuePair in dictionary)
			{
				int index = this.spaceTreeView.Nodes.Add(new LevelNode(this.m_dataManager.FindLevel(keyValuePair.Key)));
				foreach (Space space2 in keyValuePair.Value)
				{
					this.spaceTreeView.Nodes[index].Nodes.Add(new SpaceNode(space2));
				}
			}
			this.spaceTreeView.ExpandAll();
			this.spaceTreeView.Sort();
		}

		private void InitZonePara(Zone zone)
		{
			if (zone == null)
			{
				return;
			}
			this.m_PropertyMgr.Clear();
			HYProperty hyproperty = new HYProperty();
			hyproperty.Name = "ZONE_COOLING_SET_POINT_PARAM";
            hyproperty.Value = StringTools.DoubleToString(UnitConvert.CovertFromAPI((DisplayUnitType)57, zone.CoolingSetPoint), 2);
			hyproperty.Category = "夏季参数";
			hyproperty.DisplayName = "空调设计温度(℃)";
			this.m_PropertyMgr.Add(hyproperty);
			HYProperty hyproperty2 = new HYProperty();
			hyproperty2.Name = "ZONE_DEHUMIDIFICATION_SET_POINT_PARAM";
            hyproperty2.Value = StringTools.DoubleToString(UnitConvert.CovertFromAPI((DisplayUnitType)19, zone.DehumidificationSetPoint), 2);
			hyproperty2.Category = "夏季参数";
			hyproperty2.DisplayName = "空调相对湿度(%)";
			this.m_PropertyMgr.Add(hyproperty2);
			HYProperty hyproperty3 = new HYProperty();
			hyproperty3.Name = "ZONE_HEATING_SET_POINT_PARAM";
            hyproperty3.Value = StringTools.DoubleToString(UnitConvert.CovertFromAPI((DisplayUnitType)57, zone.HeatingSetPoint), 2);
			hyproperty3.Category = "冬季参数";
			hyproperty3.DisplayName = "空调设计温度(℃)";
			this.m_PropertyMgr.Add(hyproperty3);
			HYProperty hyproperty4 = new HYProperty();
			hyproperty4.Name = "ZONE_HUMIDIFICATION_SET_POINT_PARAM";
            hyproperty4.Value = StringTools.DoubleToString(UnitConvert.CovertFromAPI((DisplayUnitType)19, zone.HumidificationSetPoint), 2);
			hyproperty4.Category = "冬季参数";
			hyproperty4.DisplayName = "空调相对湿度(%)";
			this.m_PropertyMgr.Add(hyproperty4);
			HYProperty hyproperty5 = new HYProperty();
			hyproperty5.Name = "ZONE_OUTSIDE_AIR_PER_PERSON_PARAM";
            hyproperty5.Value = StringTools.DoubleToString(UnitConvert.CovertFromAPI((DisplayUnitType)66, zone.GetYJKOutDoorAirPerPerson()), 2);
			hyproperty5.Category = "新风信息";
			hyproperty5.DisplayName = "每人的新风量(m^3/h.人）";
			this.m_PropertyMgr.Add(hyproperty5);
			this.propertyGridSpace.SelectedObject = this.m_PropertyMgr;
		}

		private void InitZoneList()
		{
			this.listZoneView.Items.Add(new ListViewItem("默认"));
			foreach (Level level in this.m_dataManager.GetLevels())
			{
				this.m_dataManager.Update(level);
				foreach (Zone zone in this.m_dataManager.GetZones())
				{
					this.listZoneView.Items.Add(new ListViewItemZone(zone));
				}
			}
		}

		private void listSpaceView_ItemSelectionChanged(object sender, ListViewItemSelectionChangedEventArgs e)
		{
			if (e.IsSelected)
			{
				ListViewItemZone listViewItemZone = e.Item as ListViewItemZone;
				if (listViewItemZone != null)
				{
					this.m_currentZone = listViewItemZone.Zone;
					this.m_dataManager.CurrentZone = listViewItemZone.Zone;
					this.HighLightZone(listViewItemZone.Zone);
					this.InitSpaceTree(listViewItemZone.Zone);
					this.InitZonePara(listViewItemZone.Zone);
					return;
				}
				ListViewItem item = e.Item;
				if (item == null)
				{
					return;
				}
				if (item.Text.Equals("默认"))
				{
					this.InitSpaceTree(null);
					this.propertyGridSpace.SelectedObject = null;
				}
			}
		}

		private void HighLightZone(Zone zone)
		{
			if (zone == null)
			{
				return;
			}
			if (this.chkShowElement.Checked)
			{
				SpaceUtils.HigtLightElement(this.m_uiApp, zone.Id);
			}
		}

		private void btnOK_Click(object sender, EventArgs e)
		{
			string strVal = this.chkShowElement.Checked.ToString();
			this.SetRegKey("AutoSelElement", strVal);
		}

		private void spaceTreeView_AfterSelect(object sender, TreeViewEventArgs e)
		{
			if (e.Node.GetType().Name == typeof(SpaceNode).Name)
			{
				SpaceNode spaceNode = e.Node as SpaceNode;
				if (spaceNode == null)
				{
					return;
				}
				if (this.chkShowElement.Checked)
				{
					SpaceUtils.HigtLightElement(this.m_uiApp, spaceNode.Space.Id);
				}
			}
		}

		private void btnAdd_Click(object sender, EventArgs e)
		{
			AddSpaceManagerFrom addSpaceManagerFrom = new AddSpaceManagerFrom(this.m_dataManager);
			addSpaceManagerFrom.IsModify = false;
			if (addSpaceManagerFrom.ShowDialog() == DialogResult.OK)
			{
				Zone zone = addSpaceManagerFrom.Zone;
				ListViewItemZone focusedItem = (ListViewItemZone)this.listZoneView.Items.Add(new ListViewItemZone(zone));
				this.listZoneView.Focus();
				this.listZoneView.FocusedItem = focusedItem;
			}
		}

		private void btnModify_Click(object sender, EventArgs e)
		{
			ListViewItemZone listViewItemZone = this.listZoneView.FocusedItem as ListViewItemZone;
			if (listViewItemZone != null)
			{
				AddSpaceManagerFrom addSpaceManagerFrom = new AddSpaceManagerFrom(this.m_dataManager);
				addSpaceManagerFrom.Zone = listViewItemZone.Zone;
				addSpaceManagerFrom.IsModify = true;
				if (addSpaceManagerFrom.ShowDialog() == DialogResult.OK)
				{
					Zone zone = addSpaceManagerFrom.Zone;
					ListViewItemZone listViewItemZone2 = this.listZoneView.FocusedItem as ListViewItemZone;
					listViewItemZone2.Text = zone.Name;
					listViewItemZone2.Zone = zone;
					this.InitSpaceTree(listViewItemZone2.Zone);
				}
				return;
			}
			ListViewItem focusedItem = this.listZoneView.FocusedItem;
			if (focusedItem != null && focusedItem.Text.Equals("默认"))
			{
				YJKMessageBox.Error("默认分区不能修改!");
				return;
			}
			YJKMessageBox.Error("请选择要修改的分区！");
		}

		private void propertyGridSpace_PropertyValueChanged(object s, PropertyValueChangedEventArgs e)
		{
			if (this.m_currentZone == null)
			{
				return;
			}
			string name = e.ChangedItem.PropertyDescriptor.Name;
			double num = 0.0;
			try
			{
				num = Convert.ToDouble(e.ChangedItem.Value);
				if (name.Equals("ZONE_COOLING_SET_POINT_PARAM") || name.Equals("ZONE_HEATING_SET_POINT_PARAM"))
				{
					if (num < 13.0 || num > 113.0)
					{
						YJKMessageBox.Error("设计温度应该在13-113间");
						this.propertyGridSpace.SelectedGridItem = e.ChangedItem;
						return;
					}
				}
				else if ((name.Equals("ZONE_DEHUMIDIFICATION_SET_POINT_PARAM") || name.Equals("ZONE_HUMIDIFICATION_SET_POINT_PARAM")) && (num < 0.0 || num > 100.0))
				{
					YJKMessageBox.Error("请输入0-100之间的数值");
					this.propertyGridSpace.SelectedGridItem = e.ChangedItem;
					return;
				}
			}
			catch (Exception ex)
			{
				YJKMessageBox.Error("参数输入错误！" + ex.Message);
				this.propertyGridSpace.SelectedGridItem = e.ChangedItem;
				return;
			}
			if (name == "ZONE_COOLING_SET_POINT_PARAM")
			{
				this.m_currentZone.CoolingSetPoint = UnitConvert.CovertToAPI(num, (Autodesk.Revit.DB.DisplayUnitType)57);
				return;
			}
			if (name == "ZONE_DEHUMIDIFICATION_SET_POINT_PARAM")
			{
				this.m_currentZone.DehumidificationSetPoint = UnitConvert.CovertToAPI(num, (Autodesk.Revit.DB.DisplayUnitType)19);
				return;
			}
			if (name == "ZONE_HEATING_SET_POINT_PARAM")
			{
				this.m_currentZone.HeatingSetPoint = UnitConvert.CovertToAPI(num, (Autodesk.Revit.DB.DisplayUnitType)57);
				return;
			}
			if (!(name == "ZONE_HUMIDIFICATION_SET_POINT_PARAM"))
			{
                //name == "ZONE_OUTSIDE_AIR_PER_PERSON_PARAM";
				return;
			}
			this.m_currentZone.HumidificationSetPoint = UnitConvert.CovertToAPI(num, (Autodesk.Revit.DB.DisplayUnitType)19);
		}

		private void SpaceManagerForm_Load(object sender, EventArgs e)
		{
			base.Icon = Resource.YArchitechIcon;
			this.btnAdd.Image = Resources.AddNew16;
			this.btnModify.Image = Resources.modify16;
			this.btnDelete.Image = Resources.delete16;
			this.m_PropertyMgr = new HYPropertys();
			this.SetTreeViewFocus(this.spaceTreeView);
			this.listZoneView.HideSelection = false;
			if (this.listZoneView.Items.Count > 0)
			{
				this.listZoneView.Items[0].Selected = true;
			}
			string value = "false";
			this.GetRegKey("AutoSelElement", ref value);
			bool @checked = Convert.ToBoolean(value);
			this.chkShowElement.Checked = @checked;
		}

		private void btnDelete_Click(object sender, EventArgs e)
		{
			ListViewItemZone listViewItemZone = this.listZoneView.FocusedItem as ListViewItemZone;
			if (listViewItemZone == null)
			{
				ListViewItem focusedItem = this.listZoneView.FocusedItem;
				if (focusedItem != null && focusedItem.Text.Equals("默认"))
				{
					YJKMessageBox.Error("默认分区不能删除!");
					return;
				}
				YJKMessageBox.Error("请选择要删除的分区！");
				return;
			}
			else
			{
				if (YJKMessageBox.Show("确认要删除分区？", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
				{
					return;
				}
				Zone zone = listViewItemZone.Zone;
				this.m_dataManager.DeleteZone(zone);
				if (this.m_uiApp.ActiveUIDocument.Document.DeleteElement(zone).Count <= 0)
				{
					YJKMessageBox.Information("操作失败！");
					return;
				}
				this.listZoneView.Items.Remove(listViewItemZone);
				if (this.listZoneView.Items.Count > 0)
				{
					this.listZoneView.Select();
					this.listZoneView.Items[0].Selected = true;
					return;
				}
				this.propertyGridSpace = null;
				return;
			}
		}

		private void SetTreeViewFocus(TreeView tv)
		{
			tv.HideSelection = false;
			tv.DrawMode = TreeViewDrawMode.OwnerDrawText;
			tv.DrawNode += this.tvSpaceUse_DrawNode;
		}

		private void tvSpaceUse_DrawNode(object sender, DrawTreeNodeEventArgs e)
		{
			e.DrawDefault = true;
			if ((e.State & TreeNodeStates.Selected) != (TreeNodeStates)0)
			{
				e.Graphics.FillRectangle(Brushes.DarkBlue, e.Node.Bounds);
				Font font = e.Node.NodeFont;
				if (font == null)
				{
					font = ((TreeView)sender).Font;
				}
                e.Graphics.DrawString(e.Node.Text, font, Brushes.White, System.Drawing.Rectangle.Inflate(e.Bounds, 2, 0));
			}
			else
			{
				e.DrawDefault = true;
			}
			if ((e.State & TreeNodeStates.Focused) != (TreeNodeStates)0)
			{
                using (Pen pen = new Pen(System.Drawing.Color.Black))
				{
					pen.DashStyle = DashStyle.Dot;
                    System.Drawing.Rectangle bounds = e.Node.Bounds;
					bounds.Size = new Size(bounds.Width - 1, bounds.Height - 1);
					e.Graphics.DrawRectangle(pen, bounds);
				}
			}
		}

		private void lv_DrawNode(object sender, DrawListViewItemEventArgs e)
		{
			e.DrawDefault = true;
			if ((e.State & ListViewItemStates.Selected) != (ListViewItemStates)0)
			{
				e.Graphics.FillRectangle(Brushes.DarkBlue, e.Item.Bounds);
				Font font = null;
				if (font == null)
				{
					font = ((ListView)sender).Font;
				}
                e.Graphics.DrawString(e.Item.Text, font, Brushes.White, System.Drawing.Rectangle.Inflate(e.Bounds, 2, 0));
			}
			else
			{
				e.DrawDefault = true;
			}
			if ((e.State & ListViewItemStates.Focused) != (ListViewItemStates)0)
			{
                using (Pen pen = new Pen(System.Drawing.Color.Black))
				{
					pen.DashStyle = DashStyle.Dot;
                    System.Drawing.Rectangle bounds = e.Item.Bounds;
					bounds.Size = new Size(bounds.Width - 1, bounds.Height - 1);
					e.Graphics.DrawRectangle(pen, bounds);
				}
			}
		}

		private bool GetRegKey(string strName, ref string strVal)
		{
			string name = "Software\\Hongye\\HcLoad\\HcRevitKernel";
			RegistryKey registryKey = Registry.CurrentUser.OpenSubKey(name, true);
			if (registryKey == null || registryKey.GetValue(strName) == null)
			{
				return false;
			}
			strVal = registryKey.GetValue(strName).ToString();
			return true;
		}

		private bool SetRegKey(string strName, string strVal)
		{
			string text = "Software\\Hongye\\HcLoad\\HcRevitKernel";
			RegistryKey currentUser = Registry.CurrentUser;
			RegistryKey registryKey = currentUser.OpenSubKey(text, true);
			registryKey = currentUser.CreateSubKey(text);
			if (registryKey == null)
			{
				return false;
			}
			registryKey.SetValue(strName, strVal);
			return true;
		}

		private void propertyGridSpace_SelectedGridItemChanged(object sender, SelectedGridItemChangedEventArgs e)
		{
		}

		private DataManager m_dataManager;

		private UIApplication m_uiApp;

		private HYPropertys m_PropertyMgr;

		private Zone m_currentZone;
	}
}
